Skip to content

Babel

In the first module, we saw how JSX is transformed into plain ol’ browser-friendly JavaScript. Babel is the tool responsible for this transformation.

It's rare for developers like you or me to use Babel directly; it's generally used under-the-hood by boilerplates and meta-frameworks. That said, it's useful for us to understand at a high level how these tools build our application. In this lesson, we're going to look at what Babel is and why it's necessary.

When Babel was created in 2014, JavaScript was in the midst of a huge update, adding many wonderful language features like arrow functions 👀 and rest/spread 👀. At the time, though, very few browsers supported these features, and so they couldn't really be used responsibly; they'd cause syntax errors for most users!

The core idea was that Babel would take fancy modern JavaScript and turn it into “oldschool” JavaScript, stuff that would work properly across all browsers.

As React became more popular, Babel's responsibility grew. In addition to transforming new JS into old JS, it also began transforming JSX into plain JS. It's also able to turn TypeScript into plain JavaScript.

Let's look at an example. Suppose we've written the following code:

function RedP({ children }) {
return (
<p>
{children}
</p>
);
}

Babel will transform it into this:

"use strict";
function RedP(_ref) {
var children = _ref.children;
return React.createElement("p", null, children);
}

In this example, Babel has compiled the JSX <p> tag into a React.createElement call. It's also removed the object destructuring 👀, since not all browsers support this functionality.

This is often referred to as transpiling. We're compiling our modern JSX code into older JavaScript code that can run in a wide set of browsers.

Modern alternatives

These days, Babel isn't the only JavaScript transpiler out there. You might also see some of these tools referenced online:

  • SWC is a performance-focused alternative. In 2022, Next.js switched from Babel to SWC under-the-hood. Parcel also uses SWC.
  • The TypeScript compiler, tsc, serves many of the same functions as babel.

Ultimately, though, these tools all serve the same purpose: transforming the code we write into older, browser-friendly JavaScript. And because they come "baked in" to tools like Parcel and Next, you don't really need to know which compiler is being used.